package com.qingzhuge.manager.resolver;

import com.qingzhuge.core.annotation.security.LoginUser;
import com.qingzhuge.manager.entity.SysUser;
import com.qingzhuge.manager.service.ISysUserService;
import com.qingzhuge.web.resolver.LoginUserHandlerResolver;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;

import static com.qingzhuge.common.Constants.CURRENT_USER_ID;

/**
 * @author : zero.xiao
 * @description : 有@LoginUser注解的方法参数，注入当前登录用户
 * @date :2018/6/14 0014 下午 17:33
 * @modified :
 * @since : 1.0.0
 */
@Slf4j
@Component
public class LoginUserHandlerMethodArgumentResolver implements LoginUserHandlerResolver {
    //    @Reference(
//            version = "${qingting.service.version}",
//            application = "${dubbo.application.id}",
//            registry = "${dubbo.registry.id}"
//    )

    @Resource
    private ISysUserService userService;

    /***
     * 判断Controller层中的参数，是否满足条件，满足条件则执行resolveArgument方法，不满足则跳过。
     */
    @Override
    public boolean supportsParameter(@NotNull MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(SysUser.class) && parameter.hasParameterAnnotation(LoginUser.class);
    }

    @Override
    public Object resolveArgument(@NotNull MethodParameter parameter, ModelAndViewContainer container,
                                  @NotNull NativeWebRequest request, WebDataBinderFactory factory) {
        log.debug("有@LoginUser注解的方法参数，注入当前登录用户");
        //获取用户ID
        Object object = request.getAttribute(CURRENT_USER_ID, RequestAttributes.SCOPE_REQUEST);
        if (object == null) {
            return null;
        }
        //获取用户信息
        return userService.findById((Long) object);
    }
}
